from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from app.services.problem_service import get_problem_list_by_author, create_problem_by_author, update_problem_by_id, \
    delete_problem_by_id
from app.utils.response import success, error

problem_bp = Blueprint('problems', __name__, url_prefix='/problems')

"""
题目列表查询
"""
@problem_bp.route('', methods=['GET'])
@jwt_required()
def get_problem_list():
    author_id = get_jwt_identity()
    problems = get_problem_list_by_author(author_id)
    if problems:
        return success(problems)
    return error(msg="题目列表为空")

"""
新增题目
"""
@problem_bp.route('', methods=['POST'])
@jwt_required()
def create_problem():
    author_id = get_jwt_identity()
    data = request.get_json()
    data['creator_id'] = author_id
    result = create_problem_by_author(data)
    if result:
        return success(result)
    else:
        return error(msg='新增题目失败')

"""
编辑题目
"""
@problem_bp.route('/<int:id>', methods=['PUT'])
@jwt_required()
def update_problem(id):
    author_id = get_jwt_identity()
    data = request.get_json()
    data['id'] = id
    data['creator_id'] = author_id
    result = update_problem_by_id(data)
    if result:
        return success(result)
    else:
        return error(msg='修改题目失败')

"""
删除题目
"""
@problem_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_problem(id):
    result = delete_problem_by_id(id)
    if result:
        return success()
    else:
        return error(msg='删除题目失败')